package com.wantong.jianpu.activitys;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.wantong.jianpu.BR;
import com.wantong.jianpu.R;
import com.wantong.jianpu.base.BaseXActivity;
import com.wantong.jianpu.databinding.ActivityDeviceConfirmBinding;
import com.wantong.jianpu.event.TourDetailEvent;
import com.wantong.jianpu.viewmodels.DeviceConfirmViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Calendar;

/**
 * 巡检确认列表
 */
public class DeviceConfirmActivity extends BaseXActivity<ActivityDeviceConfirmBinding, DeviceConfirmViewModel> {
    TimePickerView popup;
    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_device_confirm;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        super.initData();
        setToolbar(binding.baseToolBar);
        setStateLayout(binding.state);
        EventBus.getDefault().register(this);
        binding.checkTimeCsv.setOnClickListener(v -> {
            showDatePicker();
        });
        binding.swipeRefresh.setOnRefreshListener(() -> {
            viewModel.loadData(true);
        });

        viewModel.refreshEvent.observe(this, aBoolean -> {
            binding.swipeRefresh.setRefreshing(aBoolean);
        });
    }

    /**
     * 日期选择器
     */
    private void showDatePicker() {
        Calendar cal = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal.set(cal2.get(Calendar.YEAR) - 5, 0, 1);

        if (popup == null) {
            popup = new TimePickerBuilder(DeviceConfirmActivity.this, (date, v) -> {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                String month = (calendar.get(Calendar.MONTH) + 1) + "";
                month = month.length() > 1 ? month : "0" + month;
                viewModel.date.setValue(calendar.get(Calendar.YEAR) + "-" + month);
            })
                    .setType(new boolean[]{true, true, false, false, false, false})
                    .setTitleText("选择时间")
                    .setRangDate(cal, cal2)
                    .build();
        }
        popup.setDate(Calendar.getInstance());
        popup.show();

    }

    /**
     * 刷新
     * @param event
     */
    @Subscribe
    public void onEvent(TourDetailEvent event){
        viewModel.loadData(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
    }
}